package com.lx.ngsl.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.util.StringUtils;

public class ResultSetUtil {

	/**
	 * 
	 * <p>Method ：extractData
	 * <p>Description : 从结果集中提取数据集合
	 *
	 * @param resultSet 结果集
	 * @param props 提取的字段名，若不输入则默认提取所有字段
	 * @return 
	 *</p>
	 */
	public static Map<String,List<String>> extractData(List<Map<String,Object>> resultSet,String ... props){
		Map<String,List<String>> data = new HashMap<>();
		if(resultSet == null || resultSet.size() == 0) {
			return data;
		}
		//确定需要提取的字段集合
		Collection<String>  set = null;
		if(props == null || props.length == 0) {
			set = resultSet.get(0).keySet();
		}else {
			set = new HashSet<>(Arrays.asList(props));
			//输入的字段都转为大写
			set.stream().map(x -> {
				if(StringUtils.hasLength(x)) {
					String p = x.toUpperCase();
					return p;
				}else {
					return "";
				}
			})
			.collect(Collectors.toSet());
		}
		//准备接数据的容器
		Iterator<String> proIt = set.iterator();
		String prop = null;
		while(proIt.hasNext()) {
			prop = proIt.next();
			if(StringUtils.hasLength(prop)) {
				data.put(prop.toLowerCase(), new ArrayList<>());
			}
		}
		//提取数据
		Iterator<Map<String, Object>> it = resultSet.iterator();
		while(it.hasNext()) {
			Map<String, Object> obj = it.next();
			proIt = set.iterator();
			while(proIt.hasNext()) {
				prop = proIt.next();
				if(StringUtils.hasLength(prop)) {
					data.get(prop.toLowerCase()).add(obj.get(prop).toString());
				}
			}
			
		}
		return data;
	}
}
